/*
 * spring-security-jwt - spring-security-jwt
 * Copyright © 2022-Present Jinan Yuanchuang Network Technology Co., Ltd. (support@topiam.cn)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.topiam.employee.sample.jwt.configuration;

import java.util.UUID;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.ExceptionHandlingConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import cn.topiam.employee.sample.jwt.authentication.JwtAuthenticationConfigurer;
import cn.topiam.employee.sample.jwt.authentication.UnAuthenticationHandler;

/**
 * SecurityConfiguration
 *
 * @author SanLi
 * Created by qinggang.zuo@gmail.com / 2689170096@qq.com on  2022/10/21 15:15
 */
@Configuration
public class JwtSampleSecurityConfiguration {

    private final ApplicationContext context;

    @Bean
    public SecurityFilterChain jwtSecurityFilterChain(HttpSecurity http) throws Exception {
        //静态资源
        http.authorizeHttpRequests(registry -> {
            registry
                .requestMatchers(new AntPathRequestMatcher(errorProperties.getPath()),
                    new AntPathRequestMatcher("/index", HttpMethod.GET.toString()),
                    new AntPathRequestMatcher("/sso/initiator", HttpMethod.POST.toString()),
                    new AntPathRequestMatcher("/css/**", HttpMethod.GET.toString()),
                    new AntPathRequestMatcher("/js/**", HttpMethod.GET.toString()),
                    new AntPathRequestMatcher("/images/**", HttpMethod.GET.toString()),
                    new AntPathRequestMatcher("/webjars/**", HttpMethod.GET.toString()),
                    new AntPathRequestMatcher("/favicon.ico", HttpMethod.GET.toString()),
                    new AntPathRequestMatcher("/actuator/health", HttpMethod.GET.toString()))
                .permitAll();
            registry.anyRequest().authenticated();
        });
        http.exceptionHandling(new Customizer<>() {
            @Override
            public void customize(ExceptionHandlingConfigurer<HttpSecurity> configurer) {
                configurer.authenticationEntryPoint(new UnAuthenticationHandler());
            }
        });
        http.csrf(AbstractHttpConfigurer::disable).formLogin(AbstractHttpConfigurer::disable);
        http.with(new JwtAuthenticationConfigurer(context), configurer -> {
        });
        return http.build();
    }

    /**
     * 用户详情
     *
     * @return {@link UserDetailsService}
     */
    @Bean
    public UserDetailsService userDetailsService() {
        return username -> User.withUsername(username).password(UUID.randomUUID().toString())
            .roles("USER").build();
    }

    /**
     * 配置密码加密
     *
     * @return {@link PasswordEncoder}
     */
    @Bean
    @ConditionalOnMissingBean(value = PasswordEncoder.class)
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    private final ErrorProperties errorProperties;

    public JwtSampleSecurityConfiguration(ApplicationContext context,
                                          ServerProperties errorProperties) {
        this.context = context;
        this.errorProperties = errorProperties.getError();
    }
}
